package com.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.community.bean.User;
import com.community.service.DictService;
import com.community.service.MenuService;
import com.community.service.UserService;
import com.community.util.Result;
import com.community.util.SessionUtil;
import com.community.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping(value = "/free")
public class LoginAction {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private DictService dictService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result adminLogin(@RequestParam String account,@RequestParam String password,
                             @RequestParam String verifyCode,HttpSession session) {

        String realverifyCode =  (String)session.getAttribute("verifyCode");
        if(!verifyCode.equalsIgnoreCase(realverifyCode)){
            return Result.error("验证码错误！");
        }
        session.removeAttribute("verifyCode");
        User user = userService.findUserByAccount(account);
        if(user == null){
            return Result.error("帐号不存在！");
        }else if(!user.getPassword().equals(password)){
            return Result.error("帐号或密码错误！");
        }else{
            SessionUtil.adminLogin(user);
            return Result.success();
        }
    }

    @RequestMapping(value = "/authImage")
    public void service(HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //删除以前的
        session.removeAttribute("verifyCode");
        session.setAttribute("verifyCode", verifyCode.toLowerCase());
        //生成图片
        int w = 100, h = 32;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    }

    @RequestMapping(value = "/logout")
    public Result clearSession(HttpSession session) {
        SessionUtil.adminLogout();
        return Result.success();
    }

    @RequestMapping(value = "/getUserInfo")
    public Result getUserInfo() {
        User user = SessionUtil.getCurAdmin();
        if(user == null){
            return Result.error("session 已过期！");
        }
        JSONObject obj = new JSONObject();
        user.setPassword(null);
        obj.put("user",user);
        obj.put("menus",menuService.getUserMenu(user));
        obj.put("allDict",dictService.allDict());

        return Result.success(obj);
    }
    
    private void config(JSONObject data){
        //data.put("imageActionName", "uploadimage"); /* 执行上传图片的action名称 */
        data.put("imageFieldName", "file");/* 提交的图片表单名称 */
        data.put("imageMaxSize", 10240000);/* 上传大小限制，单位B */
        data.put("imageAllowFiles", new String[]{".png", ".jpg", ".jpeg", ".gif", ".bmp"});/* 上传图片格式显示 */
        data.put("imageCompressEnable", true);/* 是否压缩图片,默认是true */
        data.put("imageCompressBorder", 1600);/* 图片压缩最长边限制 */
        data.put("imageInsertAlign", "none");/* 插入的图片浮动方式 */
        data.put("imageUrlPrefix", ""); /* 图片访问路径前缀 */
        data.put("imagePathFormat","/upload/ueditor"+"/size*{yyyy}{mm}{dd}{time}{rand:6}");/* 上传保存路径,可以自定义保存路径和文件名格式 */
    }

    @RequestMapping(value = "/ueditor")
    public JSONObject ueditor(@RequestParam(value="action",required = false) String action, HttpServletRequest req) {
        JSONObject ret = new JSONObject();
        try {
            if(action == null){
                ret.put("state", "command error!");
            }else if(action.equals("config")){
                config(ret);
            }else if(action.equals("uploadimage")){
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
                MultipartFile file = multipartRequest.getFile("file");
                ret = ueditorUploadImage(file);
            }else{
                ret.put("state", "command doesn't exist!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    private JSONObject ueditorUploadImage(MultipartFile file){
        JSONObject ret = new JSONObject();
        long size =file.getSize();
        if(size> 10240000){
            ret.put("state", "Uploading image size exceeds 1M！");
            return ret;
        }else{
            ret.put("size",size);
        }
        //设置图片信息
      /*  try {
            File tempDir = new File(InitServlet.APPLICATION_URL + MyConstants.TEMP_UPLOAD_PATH);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            File basePath = new File(InitServlet.APPLICATION_URL + MyConstants.UPLOAD_PATH_UEDITOR);
            if (!basePath.exists()) {
                basePath.mkdirs();
            }
            ret.put("original",file.getOriginalFilename());
            ret.put("type",".jpg");
            String nowTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            String tempPath = MyConstants.TEMP_UPLOAD_PATH+"/"+nowTime+file.getOriginalFilename();

            File f = new File(InitServlet.APPLICATION_URL+tempPath);
            file.transferTo(f);
            ret.put("url",PicUtil.zipImage(f,InitServlet.APPLICATION_URL,MyConstants.UPLOAD_PATH_UEDITOR ));
            ret.put("state","SUCCESS");
        } catch (Exception e) {
            ret.put("state", e.getMessage());
            e.printStackTrace();
        }*/
        return ret;
    }

}